﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;
using System.IO;

namespace Planetwork.Admin
{
    public partial class HomeManager : System.Web.UI.Page
    {
        public static string conStr = ConfigurationManager.AppSettings["conStr"];
        static SqlConnection mycon = new SqlConnection(conStr);
        static int pageSize = 8;
        protected void Page_Load(object sender, EventArgs e)
        {
            if(!IsPostBack)
            {
                BindData(1);
            }

            //HomeDatails 加载图片
            if(Request["imgID"] != null)
            {
                string id = Request["imgID"].ToString();
                string sql = "select ImageData from DefaultImage where id=" + id;
                SqlDataAdapter mydat = new SqlDataAdapter(sql, mycon);
                DataSet myds = new DataSet();
                mycon.Open();
                mydat.Fill(myds);
                mycon.Close();
                byte[] buffer = (byte[])myds.Tables[0].Rows[0][0];
                if(buffer.Length > 0)
                {
                    Response.Clear();
                    Response.OutputStream.Write(buffer, 0, buffer.Length);
                    Response.End();
                }
            }

            int totalPage = TotalPage();
            for(int i = 1; i <= totalPage; i++)
            {
                var btn = new Button();
                btn.Text = i.ToString();
                btn.Click += new EventHandler(Paging);
                btn.CssClass = "btn btn-default";
                this.pagingBtnGroup.Controls.Add(btn);
            }       
        }

        /// <summary>
        /// 添加主页信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void submitBtn_Click(object sender, EventArgs e)
        {
            HttpPostedFile file = image.PostedFile;
            int length = file.ContentLength;
            byte[] buffer = new byte[length];
            string imageType = file.ContentType;
            Stream steam = file.InputStream;
            steam.Read(buffer, 0, length);
            /*
            string title = this.title.ToString();
            string content = this.content.ToString();
            string about = this.about.ToString();
            */
            string sqlStr = "insert into DefaultImage (Title, Content, About, ImageData, ImageMimeType) values(@title, @content, @about, @image, @imageType)";

            SqlCommand mycmd = new SqlCommand(sqlStr, mycon);
            mycmd.Parameters.AddWithValue ("@title", this.title.Text);
            mycmd.Parameters.AddWithValue("@content", this.content.Text);
            mycmd.Parameters.AddWithValue("@about", this.about.Text);
            mycmd.Parameters.AddWithValue("@imageType", imageType);
            mycmd.Parameters.AddWithValue("@image", buffer);

            mycon.Open();
            int i = mycmd.ExecuteNonQuery();
            mycon.Close();

            if (i > 0)
                Response.Write("<script>alert('添加成功!');window.location.href ='HomeManager.aspx'</script>");
            else
                Response.Write("<script>alert('添加失败');</script>");

        }
        
        /// <summary>
        /// GridView数据源
        /// </summary>
        void BindData(int currentPage)
        {
            int skip = pageSize * (currentPage - 1);
            string sqlStr = "select top " + pageSize + " *from DefaultImage where ID not in(select top " + skip + " ID from DefaultImage)";
            SqlDataAdapter mydat = new SqlDataAdapter(sqlStr, mycon);
            DataSet myds = new DataSet();
           
            mycon.Open();
            mydat.Fill(myds);
            mycon.Close();

            if(myds.Tables[0].Rows.Count > 0)
            {
                this.showDefault.DataSource = myds.Tables[0];
                this.showDefault.DataBind();
            }
        }

        /// <summary>
        /// 删除事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void showDefault_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if(e.CommandName == "del" )
            {
                string id = e.CommandArgument.ToString();
                string sql = "delete DefaultImage where ID=" + id;
                SqlCommand mycmd = new SqlCommand(sql, mycon);

                mycon.Open();
                int i = mycmd.ExecuteNonQuery();
                mycon.Close();

                if (i > 0)
                {
                    Response.Write("<script>alert('删除成功');</script>");
                    BindData(1);
                }
                else
                {
                    Response.Write("<script>alert('删除失败');</script>");
                }
  
            }
        }

        /// <summary>
        /// 分页总数
        /// </summary>
        /// <returns></returns>
        public static int TotalPage()
        {
            SqlDataAdapter mydat = new SqlDataAdapter("select ID from DefaultImage", mycon);
            DataSet myds = new DataSet();

            mycon.Open();
            mydat.Fill(myds);
            mycon.Close();

            int i = myds.Tables[0].Rows.Count;
            i = (int)Math.Ceiling((decimal)i / pageSize);
            return i;
        }

        /// <summary>
        /// 分页事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Paging(object sender, EventArgs e)
        {
            Button btn = sender as Button;
            int currentPage;
            if (btn.Text == "首页")
                currentPage = 1;
            else if (btn.Text == "末页")
                currentPage = TotalPage();
            else
            {
                currentPage = Convert.ToInt32(btn.Text);

            }

            BindData(currentPage);

        }



    }
}